package com.maozzi.service.acl.domain.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maozzi.common.enums.BizCodeEnum;
import com.maozzi.common.exception.BizException;
import com.maozzi.common.util.ParamCheckUtil;
import com.maozzi.service.acl.domain.PermissionDomainService;
import com.maozzi.service.acl.repository.mapper.PermissionMapper;
import com.maozzi.service.acl.repository.model.Permission;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 权限 - 权限/资源 domain service
 *
 * @author maozi
 */
@Service
public class PermissionDomainServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionDomainService {

    @Override
    public Permission getPermission(Long permissionId) {
        return this.getById(permissionId);
    }

    @Override
    public List<Permission> getPermissions(List<Long> permissionIds) {
        LambdaQueryWrapper<Permission> query = Wrappers.lambdaQuery(Permission.class)
                .in(Permission::getId, permissionIds)
                .eq(Permission::getDeleted, false);

        return this.list(query);
    }

    @Override
    public Permission addPermission(Permission permission) {
        ParamCheckUtil.notNull(permission, "参数错误");

        // 检查权限码code是否重复
        this.checkCode(permission.getCode());

        permission.setId(null);
        permission.setCreateDate(null);
        permission.setModifiedDate(null);
        permission.setModifiedBy(null);

        this.save(permission);

        return permission;
    }

    /**
     * 检查权限码code是否重复
     *
     * @param code          权限码
     * @param permissionIds 权限ID
     */
    private void checkCode(String code, Long... permissionIds) {
        LambdaQueryWrapper<Permission> query = Wrappers.lambdaQuery(Permission.class)
                .eq(Permission::getCode, code)
                .eq(Permission::getDeleted, false);
        if (Objects.nonNull(permissionIds) && permissionIds.length > 0) {
            query.in(Permission::getId, (Object[]) permissionIds);
        }

        long count = this.count(query);
        if (count > 0) {
            throw new BizException(BizCodeEnum.WRONG_PARAMETERS, "权限码code重复");
        }
    }

    @Override
    public Boolean editPermission(Long permissionId, Permission permission) {
        // code 不允许被修改
        permission.setCode(null);

        LambdaUpdateWrapper<Permission> query = Wrappers.lambdaUpdate(Permission.class)
                .eq(Permission::getId, permissionId);

        return this.update(permission, query);
    }
}
